﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;
using BigTestV3.common;
using BigTestV3.xmlHelp;
using ICSharpCode.SharpZipLib.Zip;

namespace BigTestV3
{
    public partial class frmDownload : Form
    {
        public frmDownload()
        {
            InitializeComponent();
        }

        private List<DownLoadInfo> downLoad = null;
        private string xmlName = string.Empty;

        /// <summary>
        /// 初始化窗体，并加载数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DownloadLoad(object sender, EventArgs e)
        {
            Inits();
            try
            {
                if (File.Exists(FilePathTotal.DownloadInfoPath))
                {
                    var zips = xmlHelp.XmlHelper.XmlDeserializeFromFile<HtmlFileZips>(FilePathTotal.DownloadInfoPath,
                                                                                      Encoding.UTF8);

                    downLoad = new List<DownLoadInfo>();

                    foreach (HtmlFileZip name in zips.HtmlFileZip)
                    {
                        string[] arrs = name.Name.Split('_');
                        DownLoadInfo info = null;
                        if (arrs.Length == 4)
                        {
                            info = new DownLoadInfo
                                       {
                                           TestName = arrs[0],
                                           TestId = arrs[1],
                                           PaperId = arrs[2],
                                           TestTime = Path.GetFileNameWithoutExtension(arrs[3])
                                       };
                        }
                        if (info != null)
                        {
                            downLoad.Add(info);
                        }
                    }


                    if (downLoad != null)
                    {
                        dataGridView1.DataSource = downLoad;
                    }
                }
                else
                {
                    MessageBox.Show("没有下载文件");
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
          
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                DataGridViewColumn column = dataGridView1.Columns[e.ColumnIndex];
                if (column is DataGridViewButtonColumn)
                {
                    try
                    {
                        WebClient WebCnt = new WebClient();
                        var zips = xmlHelp.XmlHelper.XmlDeserializeFromFile<HtmlFileZips>(Application.StartupPath + @"\\xml\\DownloadInfo.xml", Encoding.UTF8);
                        
                        if (zips != null)
                        {
                            string file = zips.HtmlFileZip[e.RowIndex].Name;
                            string url = FilePathTotal.DownloadUrl + file;
                            string filename = GetFilePath()??"";
                            if (!string.IsNullOrEmpty(filename))
                            {
                                WebCnt.DownloadFile(url, filename + file);
                                
                                UnZip(filename + file, filename, "", true);
                                BigTestInfo bigTestInfo = xmlHelp.XmlHelper.XmlDeserializeFromFile<BigTestInfo>(filename+"\\"+xmlName, Encoding.UTF8);
                                string tempurl = FilePathTotal.DownloadMp3Url + bigTestInfo.TestPaper.CreateDate + "/" + bigTestInfo.TestPaper.Name +
                                                bigTestInfo.TestPapersDetail.First().SetPaperNumber +
                                                bigTestInfo.TestPaper.PapersID;
                                WebCnt.DownloadFile(tempurl+".mp3", filename + "\\Listen.mp3");
                                if (File.Exists(filename + file) && File.Exists(filename + file + ".mp3"))
                                {
                                    MessageBox.Show("下载成功");
                                }
                                
                            }

                            AnswerInfo info = new AnswerInfo() {Name = file};
                            xmlHelp.XmlHelper.XmlSerializeToFile(info, FilePathTotal.AnswerInfoPath,
                                                                 Encoding.UTF8);
                        }
                    }
                    catch (Exception ex)
                    {

                        MessageBox.Show(ex.Message);
                    }
                    
                }
            }
        }

        /// <summary>
        /// 初始化信息
        /// </summary>
        private void Inits()
        {
            var columnfile = new DataGridViewButtonColumn();

            columnfile.HeaderText = "下载文件";

            columnfile.Name = "Button";

            columnfile.UseColumnTextForButtonValue = true;
            columnfile.Text = "下载文件";

            

            dataGridView1.Columns.Add(columnfile);

            //var columnmp3 = new DataGridViewButtonColumn();

            //columnmp3.HeaderText = "下载听力";

            //columnmp3.Name = "Button";

            //columnmp3.UseColumnTextForButtonValue = true;
            //columnmp3.Text = "下载听力";

            //dataGridView1.Columns.Add(columnmp3);
        }

        /// <summary>
        /// 解压缩
        /// </summary>
        /// <param name="zipedFile"></param>
        /// <param name="strDirectory"></param>
        /// <param name="password"></param>
        /// <param name="overWrite"></param>
        public void UnZip(string zipedFile, string strDirectory, string password, bool overWrite)
        {

            if (strDirectory == "")
                strDirectory = Directory.GetCurrentDirectory();
            if (!strDirectory.EndsWith("\\"))
                strDirectory = strDirectory + "\\";

            using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipedFile)))
            {
                s.Password = password;
                ZipEntry theEntry;

                while ((theEntry = s.GetNextEntry()) != null)
                {
                    string directoryName = "";
                    string pathToZip = "";
                    pathToZip = theEntry.Name;
                    if (pathToZip.Contains(".xml"))
                    {
                        xmlName = pathToZip;
                    }

                    if (pathToZip != "")
                        directoryName = Path.GetDirectoryName(pathToZip) + "\\";

                    string fileName = Path.GetFileName(pathToZip);

                    Directory.CreateDirectory(strDirectory + directoryName);

                    if (fileName != "")
                    {
                        if ((File.Exists(strDirectory + directoryName + fileName) && overWrite) ||
                            (!File.Exists(strDirectory + directoryName + fileName)))
                        {
                            using (FileStream streamWriter = File.Create(strDirectory + directoryName + fileName))
                            {
                                int size = 2048;
                                byte[] data = new byte[2048];
                                while (true)
                                {
                                    size = s.Read(data, 0, data.Length);

                                    if (size > 0)
                                        streamWriter.Write(data, 0, size);
                                    else
                                        break;
                                }
                                streamWriter.Close();
                            }
                        }
                    }
                }

                s.Close();
            }
        }

        string GetFilePath()
        {
            string strPath = FilePathTotal.PathPath;
            FilePath filePath = null;
            if (File.Exists(strPath))
            {
                filePath = XmlHelper.XmlDeserializeFromFile<FilePath>(strPath, Encoding.UTF8);
            }

            if (filePath != null && File.Exists(filePath.Path))
            {
                BasicSetting setting = XmlHelper.XmlDeserializeFromFile<BasicSetting>(filePath.Path, Encoding.UTF8);
                if (setting != null)
                {
                    return setting.FilePath;
                }
            }
           return null;

        }

    }
}
